package service

import (
	"context"
	"fmt"
	"software/global"
	"software/models"
	"software/models/mongo"
	"strconv"
	"time"

	"go.mongodb.org/mongo-driver/bson"
)

/*
*
读取图片的信息
*/
func QueryPhotoById(id string) (map[string]interface{}, error) {
	var photo models.Photo
	result := global.DB.First(&photo, id)
	if result.Error != nil {
		return nil, result.Error
	}

	// 构建返回数据
	return map[string]interface{}{
		"id":           photo.ID,
		"url":          photo.URL,
		"user_id":      photo.UserID,
		"uploaded_at":  photo.UploadedAt,
		"status":       photo.Status,
		"is_hidden":    photo.IsHidden,
		"device":       photo.Device,
		"category":     photo.Category,
		"focal_length": photo.FocalLength,
		"aperture":     photo.Aperture,
		"shutter":      photo.Shutter,
		"iso":          photo.ISO,
		"taken_at":     photo.TakenAt,
		"longitude":    photo.Longitude,
		"latitude":     photo.Latitude,
	}, nil
}

// UpdatePhotoStatus 更新照片状态
func UpdatePhotoStatus(ctx context.Context, photoID int, status int) error {
	// 更新照片状态
	err := global.DB.Model(&models.Photo{}).Where("id = ?", photoID).Update("status", status).Error
	if err != nil {
		return fmt.Errorf("更新照片状态失败: %v", err)
	}

	// 如果状态设置为封禁(2)，更新 URL
	if status == 2 {
		// 获取原始照片信息
		var photo models.Photo
		err := global.DB.Where("id = ?", photoID).First(&photo).Error
		if err != nil {
			return fmt.Errorf("获取照片信息失败: %v", err)
		}

		// 更新 URL（这里假设封禁后的 URL 需要添加某种标记或修改）
		newURL := "banned=true"
		err = global.DB.Model(&models.Photo{}).Where("id = ?", photoID).Update("url", newURL).Error
		if err != nil {
			return fmt.Errorf("更新照片 URL 失败: %v", err)
		}
	}

	// 如果照片状态变为封禁或审核中，需要查询关联帖子但不自动更新状态
	if status == 0 || status == 2 {
		// 只查询相关帖子，不自动更新状态
		postIDs, err := UpdatePostStatusByImageID(ctx, photoID)
		if err != nil {
			return fmt.Errorf("查询关联帖子失败: %v", err)
		}

		// 记录找到的关联帖子，但不自动更新状态
		if len(postIDs) > 0 {
			global.Log.Infof("照片(ID:%d)状态变更为%d，发现%d个关联帖子需要手动更新状态",
				photoID, status, len(postIDs))
		}
	}

	return nil
}

// GetPhotoStatus 获取照片状态
func GetPhotoStatus(ctx context.Context, photoID uint) (int, error) {
	var photo models.Photo
	err := global.DB.Where("id = ?", photoID).First(&photo).Error
	if err != nil {
		return 0, fmt.Errorf("获取照片信息失败: %v", err)
	}

	return photo.Status, nil
}

func QueryPhotoByUserId(userId string) ([]map[string]interface{}, error) {
	var photos []models.Photo
	// 排除状态为3(已删除)的图片
	result := global.DB.Where("user_id = ? AND status != ?", userId, 3).Find(&photos)
	if result.Error != nil {
		return nil, result.Error
	}

	if len(photos) == 0 {
		return nil, fmt.Errorf("该用户暂无图片")
	}

	// 获取MongoDB集合
	collection := global.MongoDBC.Collection(mongo.Post{}.CollectionName())

	// 获取用户信息
	var user models.User
	err := global.DB.Where("id = ?", userId).First(&user).Error
	if err != nil {
		global.Log.Warnf("查询用户信息失败，用户ID: %v, 错误: %v", userId, err)
	}

	// 结果列表
	photoList := make([]map[string]interface{}, 0, len(photos))

	// 遍历照片，获取关联的帖子状态
	for _, photo := range photos {
		// 查找使用该图片的帖子
		filter := bson.M{"imageId": photo.ID, "isDelete": false}
		var post mongo.Post
		collection.FindOne(context.Background(), filter).Decode(&post)

		// 构建返回数据
		photoMap := map[string]interface{}{
			"id":           photo.ID,
			"url":          photo.URL,
			"user_id":      photo.UserID,
			"uploaded_at":  photo.UploadedAt,
			"status":       photo.Status,
			"is_hidden":    photo.IsHidden,
			"device":       photo.Device,
			"category":     photo.Category,
			"focal_length": photo.FocalLength,
			"aperture":     photo.Aperture,
			"shutter":      photo.Shutter,
			"iso":          photo.ISO,
			"taken_at":     photo.TakenAt,
			"longitude":    photo.Longitude,
			"latitude":     photo.Latitude,
			"author": map[string]interface{}{
				"id":       photo.UserID,
				"nickname": user.Nickname,
				"avatar":   user.Avatar,
			},
		}
		photoList = append(photoList, photoMap)
	}

	return photoList, nil
}

/*
*
查询最新的照片
*/
func QueryPhotoByNew() ([]map[string]interface{}, error) {
	// 使用连接查询获取照片和用户信息
	type PhotoWithAuthor struct {
		models.Photo
		AuthorName   string `gorm:"column:author_name"`
		AuthorAvatar string `gorm:"column:author_avatar"`
	}

	var photosWithAuthor []PhotoWithAuthor
	result := global.DB.Table("photo").
		Select("photo.*, user.nickname as author_name, user.avatar as author_avatar").
		Joins("LEFT JOIN user ON photo.user_id = user.id").
		Where("photo.status != ?", 3). // 排除状态为3(已删除)的图片
		Order("photo.id desc").
		Limit(10).
		Find(&photosWithAuthor)

	if result.Error != nil {
		return nil, result.Error
	}

	// 获取MongoDB集合
	collection := global.MongoDBC.Collection(mongo.Post{}.CollectionName())

	// 结果列表
	photoList := make([]map[string]interface{}, 0, len(photosWithAuthor))

	// 遍历照片，获取关联的帖子状态
	for _, photo := range photosWithAuthor {
		// 查找使用该图片的帖子
		filter := bson.M{"imageId": photo.ID, "isDelete": false}
		var post mongo.Post
		collection.FindOne(context.Background(), filter).Decode(&post)

		// 构建返回数据
		photoMap := map[string]interface{}{
			"id":           photo.ID,
			"url":          photo.URL,
			"user_id":      photo.UserID,
			"uploaded_at":  photo.UploadedAt,
			"status":       photo.Status,
			"is_hidden":    photo.IsHidden,
			"device":       photo.Device,
			"category":     photo.Category,
			"focal_length": photo.FocalLength,
			"aperture":     photo.Aperture,
			"shutter":      photo.Shutter,
			"iso":          photo.ISO,
			"taken_at":     photo.TakenAt,
			"longitude":    photo.Longitude,
			"latitude":     photo.Latitude,
			"author": map[string]interface{}{
				"id":       photo.UserID,
				"nickname": photo.AuthorName,
				"avatar":   photo.AuthorAvatar,
			},
		}
		photoList = append(photoList, photoMap)
	}

	return photoList, nil
}

func QueryTotalPhotos() (int64, error) {
	var count int64
	// 排除状态为3(已删除)的图片
	result := global.DB.Model(&models.Photo{}).Where("status != ?", 3).Count(&count)
	if result.Error != nil {
		return 0, result.Error
	}
	return count, nil
}

// QueryPhotoList 分页查询照片列表
func QueryPhotoList(page int, pageSize int, keyword string, status string) ([]map[string]interface{}, int64, error) {
	var result []map[string]interface{}
	var total int64

	// 创建查询构建器
	query := global.DB.Table("photo").Select("photo.*, user.nickname as author_name, user.avatar as author_avatar").Joins("LEFT JOIN user ON photo.user_id = user.id")

	// 排除状态为3(已删除)的图片
	query = query.Where("photo.status != ?", 3)

	// 如果有关键词，添加模糊搜索条件
	if keyword != "" {
		query = query.Where("device LIKE ? OR category LIKE ?", "%"+keyword+"%", "%"+keyword+"%")
	}

	// 处理状态筛选
	if status != "" {
		statusInt, err := strconv.Atoi(status)
		if err == nil && statusInt >= 0 && statusInt <= 2 { // 只处理0,1,2三种状态
			query = query.Where("photo.status = ?", statusInt)
		}
	}

	// 获取总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 分页查询
	offset := (page - 1) * pageSize
	var rows []struct {
		models.Photo
		AuthorName   string `gorm:"column:author_name"`
		AuthorAvatar string `gorm:"column:author_avatar"`
	}

	if err := query.Offset(offset).Limit(pageSize).Order("photo.id asc").Find(&rows).Error; err != nil {
		return nil, 0, err
	}

	// 获取MongoDB集合
	collection := global.MongoDBC.Collection(mongo.Post{}.CollectionName())

	// 构建响应数据
	for _, row := range rows {
		// 查找使用该图片的帖子
		filter := bson.M{"imageId": row.ID, "isDelete": false}
		var post mongo.Post
		collection.FindOne(context.Background(), filter).Decode(&post)

		// 构建返回数据
		photoMap := map[string]interface{}{
			"id":           row.ID,
			"url":          row.URL,
			"user_id":      row.UserID,
			"uploaded_at":  row.UploadedAt,
			"status":       row.Status,
			"is_hidden":    row.IsHidden,
			"device":       row.Device,
			"category":     row.Category,
			"focal_length": row.FocalLength,
			"aperture":     row.Aperture,
			"shutter":      row.Shutter,
			"iso":          row.ISO,
			"taken_at":     row.TakenAt,
			"longitude":    row.Longitude,
			"latitude":     row.Latitude,
			"author": map[string]interface{}{
				"id":       row.UserID,
				"nickname": row.AuthorName,
				"avatar":   row.AuthorAvatar,
			},
		}
		result = append(result, photoMap)
	}

	return result, total, nil
}

// DeletePhotoById 软删除指定 ID 的图片，将状态置为3，同时更新相关帖子
func DeletePhotoById(photoID uint) error {
	var photo models.Photo
	result := global.DB.Where("id = ?", photoID).First(&photo)
	if result.Error != nil {
		return fmt.Errorf("未找到该图片")
	}

	// 执行软删除操作（将状态更新为3）
	err := global.DB.Model(&photo).Updates(map[string]interface{}{
		"status": 3, // 3表示已删除状态
	}).Error

	if err != nil {
		global.Log.Errorf("软删除图片失败，图片ID: %v, 错误: %v", photoID, err)
		return fmt.Errorf("软删除图片失败: %v", err)
	}

	// 更新相关帖子为软删除状态
	// 获取MongoDB集合
	collection := global.MongoDBC.Collection(mongo.Post{}.CollectionName())

	// 构建查询条件：找到使用该图片且未删除的帖子
	filter := bson.M{
		"imageId":  int64(photoID),
		"isDelete": false,
	}

	// 构建更新内容
	update := bson.M{
		"$set": bson.M{
			"isDelete":   true,
			"updateTime": time.Now(),
		},
	}

	// 执行更新操作
	updateResult, err := collection.UpdateMany(context.Background(), filter, update)
	if err != nil {
		global.Log.Errorf("软删除关联帖子失败: %v", err)
		return fmt.Errorf("软删除关联帖子失败: %v", err)
	}

	global.Log.Infof("软删除图片成功，图片ID: %d，同时软删除了 %d 个关联帖子",
		photoID, updateResult.ModifiedCount)

	return nil
}

// QueryPhotoCategoryStats 统计作品分类占比
func QueryPhotoCategoryStats() ([]map[string]interface{}, error) {
	type Result struct {
		Category string
		Count    int64
	}
	var results []Result

	// 查询每个分类的数量，排除状态为3(已删除)的图片
	err := global.DB.Model(&models.Photo{}).
		Select("category, count(*) as count").
		Where("category != '' AND status != ?", 3).
		Group("category").
		Find(&results).Error

	if err != nil {
		return nil, err
	}

	// 计算总数
	var total int64
	for _, r := range results {
		total += r.Count
	}

	// 计算百分比
	var stats []map[string]interface{}
	for _, r := range results {
		percentage := float64(r.Count) / float64(total) * 100
		stats = append(stats, map[string]interface{}{
			"category":   r.Category,
			"count":      r.Count,
			"total":      total,
			"percentage": fmt.Sprintf("%.2f%%", percentage),
		})
	}

	return stats, nil
}

// QueryTotalByStatus 统计指定状态的照片数量
func QueryTotalByStatus(status int) (int64, error) {
	var count int64
	result := global.DB.Model(&models.Photo{}).Where("status = ?", status).Count(&count)
	if result.Error != nil {
		return 0, result.Error
	}
	return count, nil
}
